import { useEffect, useState } from 'react'
import { Outlet, useNavigate } from 'react-router-dom'
import { Button, Menu } from 'tdesign-react'
import { ChartComboIcon, TreeRoundDotIcon, ViewListIcon } from 'tdesign-icons-react'
import { useMeta } from '@/stores'
import styles from './index.module.less'
import type { MenuValue } from 'tdesign-react'
import { MainPageHeader } from '@/components/Header'

const MenuItem = Menu.MenuItem

type MenuListItemType = {
  label: string
  path: string
  key: string
  meta: {
    requireAuth: boolean
    title: string
    key: string
  }
  icon: any
}

type MenuListType = Array<MenuListItemType>

const MainPage = (props: any) => {

  const { meta } = useMeta((state) => state)
  const navigate = useNavigate()
  const [activateMenu, setActivateMenu] = useState<MenuValue>('')
  const [authMenuList, setAuthMenuList] = useState<any>([])
  const [collapsed, setCollapsed] = useState<boolean>(true)

  const baseMenuList: MenuListType = [
    {
      label: '数据大屏',
      path: '/data-viewer',
      key: 'data-viewer',
      meta: {
        requireAuth: false,
        title: '数据大屏',
        key: 'data-viewer'
      },
      icon: <ChartComboIcon />
    },
    {
      label: '组织架构',
      path: '/organization',
      key: 'organization',
      meta: {
        requireAuth: false,
        title: '组织架构',
        key: 'organization'
      },
      icon: <TreeRoundDotIcon />
    },
  ]


  useEffect(() => {
    const _authMenuList = [...baseMenuList]
    navigateToDefaultRoute(_authMenuList)
    setActivateMenu(_authMenuList[0].path)
    setAuthMenuList(_authMenuList)
    console.log('执行了一次')
  }, [])

  const navigateToDefaultRoute = (menuList: any) => {
    if (menuList.length > 0) {
      navigate(menuList[0].path)
    }
  }


  const onMenuExpand = () => {
  }

  const onMenuItemClick = ({ value }: { value: MenuValue}) => {
    navigate(value as string)
  }

  const renderTailMenu = (menuItem: any, index: number) => {
    return <MenuItem
      key={menuItem.key}
      icon={menuItem.icon}
      value={menuItem.path}
      onClick={onMenuItemClick}
    >{menuItem.label}</MenuItem>
  }

  return <div className={styles.MainPage}>
    <MainPageHeader />
    <div className={styles.wrapper}>
      <Menu
        value={activateMenu}
        expandType='normal'
        collapsed={collapsed}
        onExpand={onMenuExpand}
        operations={
          <Button
            variant='text'
            shape='square'
            icon={<ViewListIcon />}
            onClick={() => setCollapsed(!collapsed)}
          />
        }
        onChange={(menuKey: MenuValue) => { setActivateMenu(menuKey) }}
      >
        {
          authMenuList.map((menuItem: MenuListItemType, index: number) => {
            return renderTailMenu(menuItem, index)
          })
        }
      </Menu>
      <div className={styles.content}>
        <Outlet />
      </div>
    </div>
  </div>
}

export default MainPage
